/**
 * 
 */
package de.oszimtcc.framework;

import de.oszimtcc.framework.BaseActivity;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.TextUtils;
import android.util.Log;

/**
 * @author Kooki
 *
 */
public abstract class BaseApplication extends Application
{
	private String APP_NAME_SHORT = "AppNameShort";
	private String APP_NAME = "FullAppName";
	private  String LOG_TAG = APP_NAME;
		
	private int clientVersionCode;
	private String clientVersionName;
	private String language = "de";
	
	protected BaseActivity activity;
	
	public void onCreate(String pAppShortName,String pAppFullName,String pAppLanguage) 
	{
		APP_NAME_SHORT = pAppShortName;
		APP_NAME = LOG_TAG = pAppFullName;
		language = pAppLanguage;
		gatherAppVersion();
		String language = getContext().getResources().getConfiguration().locale.getLanguage();
		this.language = language.substring(0, 2).toLowerCase();
		Logger.Info("Initialisation complete, Applicationversion = " + clientVersionCode + ", Applicationlanguage = " + language);
	};
	
	public String getAppLanguage() 
	{
		return language;
	}

	public  String getAppAndroidId() 
	{
		String androidId = android.provider.Settings.Secure.getString(getContext().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
		if(androidId==null) 
		{
			androidId="AndroidEmulator";
		}
		return androidId;
	}

	public int getAppClientVersionCode() 
	{
		if(clientVersionCode==0) 
		{
			gatherAppVersion();
		}
		return clientVersionCode;
	}
	
	public String getAppClientVersionName() 
	{
		if(TextUtils.isEmpty(clientVersionName)) 
		{
			gatherAppVersion();
		}
		return clientVersionName;
	}
	
	private void gatherAppVersion() 
	{
		PackageInfo pi;
    	try 
    	{
    		pi = getContext().getPackageManager().getPackageInfo(this.getPackageName(), 0);
    		clientVersionCode = pi.versionCode;
    		clientVersionName = pi.versionName;
    	} 
    	catch (NameNotFoundException e) 
    	{
    		Logger.Error("Exception on gathering Appversion : " + e.getStackTrace());
    	}
	}
	
	public Context getContext() 
	{
		return getApplicationContext();
	}
	
    public BaseActivity getActivity()
    {
    	return activity;
    }	
    public void setActivity(BaseActivity activity)
    {
    	this.activity = activity;
    }
    
	@Override
	public void onLowMemory() 
	{
		super.onLowMemory();
		Logger.Debug("Detect low Memory...clear cache ***TODO***");
		// TODO
	}
	
	@Override
	public void onTerminate() 
	{
		Logger.Debug(" was terminated.");
		super.onTerminate();
	}
}
